﻿// --------------------------------------------------------------------------
// FileName	：	DataBind.js
// Remark	：	数据绑定及客户端验证脚本
// --------------------------------------------------------------------------
// VERSION		AUTHOR		DATE			CONTENT    E-mail
// 1.0			席吉波	    2010-05-21	    创建       KevinXi10@163.com
//说明：如有疑问请联系我 QQ 458034191或上面的邮件地址
// 修改日志：
// 1: 修改人：席吉波 修改日期：2011-01-11
//    备注：  A:增加控件的客户端绑定功能，在启用客户端绑定时 ClientDataBind=true
//              需指定操作类型OperState类型、service路径及service方法。
//            B:为兼容以前版本默认为非客户端绑定
//2：修改人：席吉波 修改日期：2012-10-20
//    备注：  A.完善客户端绑定功能(将客户端的JSON实体和操作命令发送给服务)
//            B.服务器端返回结果后，可执行用户自定义js方法（参数：JSON实体）
// --------------------------------------------------------------------------
(function () {
    var scriptName = "DataBind";

    function execute() {

        Type.registerNamespace('Kevin.Controls');

        var $DataBind = Kevin.Controls.DataBind = function (element) {

            $DataBind.initializeBase(this, [element]);

            this.validList = null; 		//ClientVdtData List.
            this.validControls = null;       // Control and ClientVdtData List.
            this.errorMessages = null; 	//errormessage List.

            this.errorImg = null;
            this.isValidate = true; 		//validate result.

            this._validButtons = null;      //触发验证的控件
            this._divErrorMessages = null;
            this._errorWindow = null;
            this._IsControlsValueChanged = true;
            this._clientDataBind = false;       //是否启用客户端绑定
            this.commandItemList = null;        //客户端命令按钮集合
            this._cache = null;             //缓存，用于客户端绑定
            this._currentClickedButton = null;
            this._servicePath = null;   //启用客户端绑定时业务操作的web服务路径
            this._serviceMethod = null; //启用客户端绑定时业务操作的WebMethod
            this._operationMode = null; //启用客户端绑定时业务操作的操作模式
            this._addOperationControlID = null;     //新增按钮ID
            this._addControl = null;
            this._editOperationControlID = null;    //编辑按钮ID
            this._editControl = null;
            this._delOperationControlID = null;     //删除按钮ID
            this._delControl = null;
            this._applyOperationControlID = null;   //申报按钮ID
            this._applyControl = null;
            this._clearOperationControlID = null;   //清空界面数据按钮ID
            this._clearControl = null;
            this._errorPopUp = null;                //出错提示气泡
            this._errorControlList = null;  //用于填充录入错误数据的控件ID
        }

        $DataBind.prototype = {
            initialize: function () {
                $DataBind.callBaseMethod(this, "initialize");

                checkFormDataHandler = Function.createDelegate(this, this.checkFormData);
                checkDataHandler = Function.createDelegate(this, this.checkData);
                formatDataHandler = Function.createDelegate(this, this.formatData);
                //onlyNumHandler = Function.createDelegate(this, this.onlyNum);
                //onlyFloatHandler = Function.createDelegate(this, this.onlyFloat);

                this.validControls = new Array();
                this.errorMessages = new Array();
                this.createValidators();
                this.addEventToValidControls();
                this.initOperationControls();
                this._initCache();
                //this.buildErrorDialog();//为保证和徐侠君的风格一致，直接alert错误信息
            },

            dispose: function () {
                this.validList = null;
                this.validControlList = null;
                this.errorMessages = null;
                this._validButtons = null;
                this._divErrorMessages = null;
                this._errorWindow = null;
                $DataBind.callBaseMethod(this, 'dispose');
            },

            createValidators: function () {
                if (!this.validList) {
                    if (!this._clientDataBind) {
                        this.validList = Sys.Serialization.JavaScriptSerializer.deserialize($get(this.get_element().id + "_ClientState").value);
                    }
                    else {
                        this.validList = Sys.Serialization.JavaScriptSerializer.deserialize($get(this.get_element().id + "_ClientState").value).ClientValidations;
                        this.commandItemList = Sys.Serialization.JavaScriptSerializer.deserialize($get(this.get_element().id + "_ClientState").value).CommandItemList;
                    }
                }
                for (i = 0; i < this.validList.length; i++) {
                    var control = $get(this.validList[i].ControlID);
                    if (control) {
                        this.validControls.push(new Array(control, this.validList[i]));
                    }
                }
            },
            get_validButtons: function () {
                return this._validButtons;
            },

            set_validButtons: function (value) {
                if (this._validButtons !== value) {
                    this._validButtons = value;
                    this.raisePropertyChanged('validButtons');

                }
            },

            updateValidButtonsDisable: function (value) {
                if (this._validButtons) {
                    var validButtons = this._validButtons.split(',');
                    var i = 0;
                    for (i = 0; i < validButtons.length; i++) {
                        $get(validButtons).disabled = value;
                    }
                }
            },
            loadClientState: function () {
                if (this._clientStateField.value == '' || this._clientStateField.value == 'undefined') {
                    return;
                }
                this.validList = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value);
            },
            saveClientState: function () {
                return Sys.Serialization.JavaScriptSerializer.serialize(this._clientStateField.value);
            },
            get_clientStateField: function () {
                return this._clientStateField;
            },
            set_clientStateField: function (value) {
                if (this._clientStateField != value) {
                    this._clientStateField = value;
                    this.raisePropertyChanged('clientStateField');
                }
            },
            findvalidControl: function (control) {
                if (control) {
                    for (n = 0; n < this.validControls.length; n++) {
                        if (control == this.validControls[n][0]) {
                            return this.validControls[n];
                        }
                    }
                }
                return null;
            },
            initOperationControls: function () {

                if (!this._clientDataBind) {
                    return;
                }
                if (!this.commandItemList) {
                    return;
                }

                for (var index in this.commandItemList) {
                    var cmd = this.commandItemList[index];
                    var ctr = $get(cmd.ControlID);
                    if (ctr) {
                        $addHandler(ctr, "click", Function.createDelegate(this, Function.createCallback(this.commandButtonClick, cmd)))
                    }
                }
            },
            commandButtonClick: function (e, cmd) {
                this._currentClickedButton = e.target;
                if (cmd.IsValidate) {
                    if (!this.checkFormData(e)) {
                        return;
                    }
                }

                this._currentClickedButton.disabled = true;
                this.InvokeWebMethod(cmd);

            },

            //
            clearCurrentPageData: function () {
                var objs = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value).ClientBindItemList;
                for (var d in objs) {
                    //excute this clear method
                    eval(objs[d].ClearMethod);
                }
            },

            addEventToValidControls: function () {

                if (!this.validControls) return;
                //add IsValidateOnSubmit Event from ClientVdtData
                if (this.validControls.length > 0 && this.validControls[0][1].IsValidateOnSubmit) {
                    //$addHandler(document.forms[0], "submit", Function.createDelegate(this, this.checkFormData));
                    if (this._validButtons) {
                        var validButtons = this._validButtons.split(',');
                        for (var i = 0; i < validButtons.length; i++) {
                            var validBtn = $get(validButtons[i])//Added 2010-06-17
                            if (validBtn) {
                                $addHandler(validBtn, "click", Function.createDelegate(this, this.checkFormData));
                            }
                        }
                    }
                }

                for (i = 0; i < this.validControls.length; i++) {
                    if (this.validControls[i][1].CvtList && this.validControls[i][1].CvtList.length > 0) {
                        if (this.validControls[i][1].IsValidateOnBlur) {
                            //$addHandler(this.validControls[i][0], "change", Function.createDelegate(this, this.checkData));
                        }
                    }
                    var callBack = Function.createCallback(this._ClientValidation, { context: this.validControls[i][1] });
                    $addHandler(this.validControls[i][0], "blur", Function.createDelegate(this, callBack));
                    //continue;
                    if (this.validControls[i][1].FormatString.length > 0) {
                        //$addHandler(this.validControls[i][0], "change", Function.createDelegate(this, this.formatData));
                    }
                    if (this.validControls[i][1].IsOnlyNum)//add check user input events
                    {
                        this.validControls[i][0].setAttribute("style", "ime-mode:Disabled");
                        //$addHandler(this.validControls[i][0], "blur", Function.createDelegate(this, this.onlyNum));

                    }
                    else if (this.validControls[i][1].IsFloat) {
                        this.validControls[i][0].setAttribute("style", "ime-mode:Disabled");
                        //$addHandler(this.validControls[i][0], "blur", Function.createDelegate(this, this.onlyFloat));

                    }
                    if (this.validControls[i][1].IsRequired) {
                        this.validControls[i][0].setAttribute("class", "RequiredInput");  //firfox 及其他浏览器
                        this.validControls[i][0].setAttribute("className", "RequiredInput"); //IE Only
                        if (!this.validControls[i][1].IsFloat || !this.validControls[i][1].IsOnlyNum) {
                            //$addHandler(this.validControls[i][0], "blur", Function.createDelegate(this, this._isRequird));
                        }
                    }
                }

            },


            addExEvent: function (control, func, isValidateonblur, errorMsg)//add ExEvents,params: target control ,callback function ,isValidateonblur,errorMsg
            {
                var eItem = new Object();
                eItem.ControlID = control.id;
                eItem.IsValidateOnBlur = isValidateonblur;
                eItem.Func = func;
                eItem.errorMsg = errorMsg;
                this.validControls.push(new Array(control, eItem));
                if (eItem.IsValidateOnBlur) {
                    $addHandler(control, "change", Function.createDelegate(this, func));
                }
            },
            InvokeWebMethod: function (cmd) {
                var method = this._serviceMethod;
                if (cmd.ServiceMethod != "") {
                    method = cmd.ServiceMethod;
                }
                if (this._servicePath && method) {
                    var obj = this.getJsonEntity(cmd.CommandType);
                    var params = { jsonEntity: obj.Entity, operationMode: obj.CmdType };
                    if (this._webRequest) {
                        // abort the previous web service call if we 
                        // are issuing a new one and the previous one is 
                        // active.
                        this._webRequest.get_executor().abort();
                        this._webRequest = null;

                    }
                    if (cmd.OnOperationPre) {
                        var resultPre = $KevinXi.execFunByName(cmd.OnOperationPre, window, obj.Entity);
                        if (!resultPre) {
                            this._currentClickedButton.disabled = false;
                            return;
                        }
                    }
                    //this._pageIndex = pageIndex;
                    //this.setClientStateNull();
                    this._webRequest = Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), method, false, params,
                                                        Function.createDelegate(this, function (result) {
                                                            if (result.Successed) {
                                                                if (cmd.CallbackMethod) {
                                                                    var method = cmd.CallbackMethod;
                                                                    //2012-10-27
                                                                    $KevinXi.execFunByName(method, window, result.Object);
                                                                    //window[method].call(this, result.Object);
                                                                }
                                                            }
                                                            else {
                                                                alert(result.ErrorMsg);
                                                            }
                                                            this._currentClickedButton.disabled = false;
                                                        }),
                                                        Function.createDelegate(this, this._onMethodFailed),
                                                        null);
                }
            },
            _onMethodComplete: function (result) {
                eval(data);
            },
            _onMethodFailed: function (e) {
                alert("调用服务失败！" + e._message);
                this._currentClickedButton.disabled = false;
            },
            _initCache: function () {
                //缓存初始化
                if (!this._cache) {
                    this._cache = {};
                }
                var objs = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value).ClientBindItemList;
                for (var d in objs) {
                    if (objs[d].IsPrimaryKey) {
                        var method = objs[d].Method;
                        var data = null;
                        if (method) {
                            data = window[method].call(this, objs[d].ID);
                        } else {
                            data = $KevinXi.getControlValue(objs[d].ID);
                        }
                        if (!data) {
                            this._cache = {};
                            break;
                        }
                        else {
                            this._cache[objs[d].Name] = data;
                        }
                    }
                }
            },
            getJsonEntity: function (opMode) {
                var objs = Sys.Serialization.JavaScriptSerializer.deserialize(this._clientStateField.value).ClientBindItemList;
                var jsonItemList = new Array();
                var result = {};
                var entity = {};
                //先判断状态
                if (opMode == "Save") {
                    for (var d in objs) {
                        var method = objs[d].Method;
                        var data = null;
                        if (method) {
                            data = window[method].call(this, objs[d].ID);
                        } else {
                            data = $KevinXi.getControlValue(objs[d].ID);
                        }
                        if (objs[d].IsPrimaryKey) {
                            if (data == "undefined" || data == "") {
                                //此时应该为新增状态
                                result.CmdType = "Add";
                            }
                            else {
                                //此时应该为修改状态
                                result.CmdType = "Edit";
                            }
                            break;
                        }
                    }
                }
                else {
                    result.CmdType = opMode;
                }

                for (var d in objs) {
                    var method = objs[d].Method;
                    var data = null;
                    if (method) {
                        data = window[method].call(this, objs[d].ID);
                    } else {
                        data = $KevinXi.getControlValue(objs[d].ID);
                    }
                    if (this._cache[objs[d].Name]) {
                        //此时肯定已经操作过了，应该是非新增操作
                        if (this._cache[objs[d].Name] != data || objs[d].IsPrimaryKey || result.CmdType === "Add") {
                            entity[objs[d].Name] = data;
                            this._cache[objs[d].Name] = data
                        }
                    } else {
                        //缓存中无值  肯定不是新增状态
                        if (data != "") {
                            entity[objs[d].Name] = data;
                            this._cache[objs[d].Name] = data
                        }
                    }
                }
                var entityJson = Sys.Serialization.JavaScriptSerializer.serialize(entity);
                result.Entity = entityJson;
                return result;
            },
            checkData: function (e) {
                this.errorMessages = new Array();
                var isvalidte = false;
                var validControl = this.findvalidControl(e.target);
                if (validControl == null) return;
                isvalidte = this.validateData(e.target[validControl[1].ValidateProp], validControl[1]);
                if (!isvalidte) {
                    this.showError(e.target, false);
                }
                return isvalidte;
            },

            checkFormData: function (e) {
                var isvalidte = true;
                isvalidte = this.checkAllData();
                if (!isvalidte && this.errorMessages.length > 0) {

                    alert(this.errorMessages.join('\n'));
                    this.errorMessages = new Array();
                    e.preventDefault(); //firefox 取消
                    //为保证和徐侠君的风格一致，直接alert错误信息
                    /*
                    this._divErrorMessages.innerHTML = "<br>";
                    for (var i = 0; i < this.errorMessages.length; i++) {
                    this._divErrorMessages.innerHTML += "<li><p>" + this.errorMessages[i] + "</p></li>";
                    }
                    this._divErrorMessages.innerHTML += "<br><hr>";
                    this._errorWindow.show();
                    this.errorMessages = new Array();
                    e.preventDefault();
                    e.stopPropagation();
                    //*/
                }
                return isvalidte;
            },
            checkAllData: function () {
                var isvalidte = true;
                this.errorMessages = new Array();
                for (k = 0; k < this.validControls.length; k++) {
                    if (this.validControls[k][1].Func) {
                        if (!this.validControls[k][1].Func()) {
                            isvalidte = false;
                        }
                        if (!isvalidte) {
                            this.errorMessages.push(this.validControls[k][1].errorMsg);
                        }
                    }
                    else if (!this.validateData(this.validControls[k][0][this.validControls[k][1].ValidateProp], this.validControls[k][1])) {
                        isvalidte = false;
                    }
                }
                this.isValidate = isvalidte;
                return isvalidte;
            },

            validateData: function (cvalue, validator) {
                var isvalidte = false;
                if (typeof (cvalue) == 'undefined') return true; //can not validate data,renturn true;
                if (!validator.CvtList && validator.CvtList.length <= 0) return true;
                if (validator.IsAnd) {
                    isvalidte = this.andValidateData(cvalue, validator.CvtList);
                }
                else {
                    isvalidte = this.orValidateData(cvalue, validator.CvtList);
                }
                return isvalidte;
            },

            orValidateData: function (cvalue, vadlist) {
                for (i = 0; i < vadlist.length; i++) {
                    if (vadlist[i].VType == 0) {
                        if (this.rangeCheck(cvalue, vadlist[i])) return true;
                    }
                    else if (vadlist[i].VType == 1) {
                        if (this.expressionCheck(cvalue, vadlist[i])) return true;
                    }
                    else if (vadlist[i].VType == 2) {
                        if (this.requirdCheck(cvalue, vadlist[i])) return true;
                    }
                }
                return false;
            },

            andValidateData: function (cvalue, vadlist) {
                for (i = 0; i < vadlist.length; i++) {
                    if (vadlist[i].VType == 0) {
                        if (!this.rangeCheck(cvalue, vadlist[i])) return false;
                    }
                    else if (vadlist[i].VType == 1) {
                        if (!this.expressionCheck(cvalue, vadlist[i])) return false;
                    }
                    else if (vadlist[i].VType == 2) {
                        if (!this.requirdCheck(cvalue, vadlist[i])) return false;
                    }
                }
                return true;
            },

            rangeCheck: function (cvalue, vadItem) {
                var isvalidte = false;
                var lowerBound;
                var upperBound;
                var sourcevalue;
                if (vadItem.DType == 0 || vadItem.DType == 3) {
                    cvalue = cvalue.replace(/,/g, ''); //convert to int
                }
                if (vadItem.DType == 0) {
                    if (!cvalue.toString().match('^[0-9]*$')) {
                        this.errorMessages.push(vadItem.MessageTemplate);
                        return false;
                    }
                    sourcevalue = parseInt(cvalue);
                    lowerBound = parseInt(vadItem.LowerBound);
                    upperBound = parseInt(vadItem.UpperBound);
                }
                else if (vadItem.DType == 2) {
                    sourcevalue = this.parseStrToDate(cvalue);
                    lowerBound = this.parseStrToDate(vadItem.LowerBound);
                    upperBound = this.parseStrToDate(vadItem.UpperBound);
                }
                else if (vadItem.DType == 3) {
                    sourcevalue = parseFloat(cvalue);
                    lowerBound = parseFloat(vadItem.LowerBound);
                    upperBound = parseFloat(vadItem.UpperBound);
                }
                else if (vadItem.DType == 4) {
                    sourcevalue = cvalue.length;
                    lowerBound = vadItem.LowerBound;
                    upperBound = vadItem.UpperBound;
                }
                else {
                    lowerBound = vadItem.LowerBound;
                    upperBound = vadItem.UpperBound;
                }
                if (sourcevalue < lowerBound || sourcevalue > upperBound) {
                    isvalidte = false;
                    this.errorMessages.push(vadItem.MessageTemplate);
                }
                else {
                    isvalidte = true;
                }
                return isvalidte;
            },

            expressionCheck: function (cvalue, vadItem) {
                if (vadItem.DType == 0 || vadItem.DType == 3) {
                    cvalue = cvalue.replace(/,/g, ''); //convert to int
                }
                var isvalidte = false;
                isvalidte = cvalue.toString().match(vadItem.Expression);
                if (!isvalidte) {
                    this.errorMessages.push(vadItem.MessageTemplate);
                }
                return isvalidte;
            },
            requirdCheck: function (cvalue, vadItem) {
                var isvalidte = false;
                isvalidte = cvalue.trim().length > 0;
                if (!isvalidte) {
                    this.errorMessages.push(vadItem.MessageTemplate);
                }
                return isvalidte;
            },
            parseStrToDate: function (str) {
                if (typeof (str) == 'Date') return str;
                var dar = str.replace(/\-0/g, "-").split("-");
                if (dar.length == 3) {
                    dar = new Array(parseInt(dar[0]), parseInt(dar[1]) - 1, parseInt(dar[2]));
                }
                else {
                    dar = new Array(1, 1, 1);
                }

                var tar = str.replace(/\-0/g, ":").split(":");
                if (tar.length == 3) {
                    tar = new Array(parseInt(tar[0]), parseInt(tar[1]) - 1, parseInt(tar[2]));
                }
                else {
                    tar = new Array(0, 0, 0);
                }

                return Date.parse(new Date(dar[0], dar[1], dar[2]), tar[0], tar[1], tar[2]);
            },

            showError: function (target, isValt) {
                alert(this.errorMessages.join('\n'));
                //

                this.errorMessages = new Array();
            }, //end  ShowError
            buildErrorDialog: function () {
                var divID = this.get_element().id;
                var divConfirm = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["dialog"],
                    properties: {
                        id: "divConfirm" + divID
                    }
                }, document.body);
                divConfirm.style.width = "200px";
                var divConfirmTitle = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["title"],
                    properties: {
                        id: "divConfirmTitle" + divID
                    }
                }, divConfirm);
                var divConfirmTitle_info = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["info"],
                    properties: {
                        id: "divConfirmTitle_info" + divID

                    }
                }, divConfirmTitle);
                divConfirmTitle_info.innerHTML = "错误提示！";
                var divConfirmTitle_close = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["ico"],
                    properties: {
                        id: "divConfirmTitle_close" + divID

                    }
                }, divConfirmTitle);
                var divConfirm_body = $common.createElementFromTemplate({
                    nodeName: "div",
                    cssClasses: ["content"],
                    properties: {
                        id: "divConfirm_body" + divID

                    }
                }, divConfirm);

                //divConfirm_body.style.width = "200px";
                //divConfirm_body.style.height = "150px";
                this._divErrorMessages = $common.createElementFromTemplate({
                    nodeName: "div",
                    properties: {
                        id: "divConfirm_content" + divID

                    }
                }, divConfirm_body);
                this._divErrorMessages.innerHTML = "<br>" + this.errorMessages.join('\n') + "<br><hr>";
                var btnConfirmOk = $common.createElementFromTemplate({
                    nodeName: "input",
                    properties: {
                        id: "divConfirm_btnOK" + divID,
                        type: "button",
                        value: "确定"
                    }
                }, divConfirm_body);
                this._errorWindow = $create(Sys.Extended.UI.ModalPopupBehavior,
                        { "DropShadow": false,
                            "PopupControlID": divConfirm.id,
                            "PopupDragHandleControlID": divConfirmTitle.id,
                            "id": "ModalPopupBehaviorError" + this.get_element().id,
                            "BackgroundCssClass": "modalBackground",
                            "repositionMode": 2,
                            "OkControlID": btnConfirmOk.id,
                            "CancelControlID": divConfirmTitle_close.id
                        }, null, null, this.get_element());
            }, //end buildErrorDialog
            _ClientValidation: function (e, args) {
                if (args.context.IsRequired) {
                    if (this.isRequirdValidation(e) == false) {
                        return;
                    }
                }
                if (args.context.IsOnlyNum) {
                    this.onlyNumValidation(e);
                }
                if (args.context.IsFloat) {
                    this.onlyFloatValidation(e);
                }
            },
            onlyNumValidation: function (ev) {
                if (!ev.target.value.length > 0) {
                    Sys.UI.DomElement.removeCssClass(ev.target, "validatorCalloutHighlight");
                    this._popErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(false);
                    this._hideTootips();
                    return true;
                }
                var isvalidte = ev.target.value.toString().match("^^-?\\d+$");
                if (!isvalidte) {
                    Sys.UI.DomElement.addCssClass(ev.target, "validatorCalloutHighlight");

                    this._showTooltips(ev.target, "请输入整数.");
                    this._pushErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(true);
                    return false;
                }
                else {
                    Sys.UI.DomElement.removeCssClass(ev.target, "validatorCalloutHighlight");
                    this._hideTootips();
                    this._popErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(false);
                    return true;
                }
                return false;
            },
            onlyFloatValidation: function (ev) {
                //var obj = this;
                if (!ev.target.value.length > 0) {
                    Sys.UI.DomElement.removeCssClass(ev.target, "validatorCalloutHighlight");
                    this._popErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(false);
                    this._hideTootips();
                    return true;
                }
                var isvalidte = ev.target.value.toString().match("^\\d+(\\.\\d+)?$");
                if (!isvalidte) {
                    Sys.UI.DomElement.addCssClass(ev.target, "validatorCalloutHighlight");

                    this._showTooltips(ev.target, "请输入数字.");
                    this._pushErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(true);
                    return false;
                }
                else {
                    Sys.UI.DomElement.removeCssClass(ev.target, "validatorCalloutHighlight");

                    this._hideTootips();
                    this._popErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(false);
                    return true;
                }
                return false;
            },
            isRequirdValidation: function (ev) {
                var val = ev.target.value
                if (ev.target.value.length > 0) {
                    Sys.UI.DomElement.removeCssClass(ev.target, "validatorCalloutHighlight");
                    this._hideTootips();
                    this._popErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(false);
                    return true;
                }
                else {
                    Sys.UI.DomElement.addCssClass(ev.target, "validatorCalloutHighlight");
                    this._showTooltips(ev.target, "该项不能为空.");
                    this._pushErrorControls(ev.target.id);
                    this._setValidateButtonsDisable(true);
                    return false;
                }
                return false;
            },
            _setValidateButtonsDisable: function (val) {
                if (this._validButtons) {
                    if (this._errorControlList) {
                        if (this._errorControlList.length > 0 && !val)
                            return;
                    }
                    var validButtons = this._validButtons.split(',');
                    for (var i = 0; i < validButtons.length; i++) {
                        var validBtn = $get(validButtons[i])//Added 2010-06-17
                        if (validBtn) {
                            validBtn.disabled = val;
                            //$addHandler(validBtn, "click", Function.createDelegate(this, this.checkFormData));
                        }
                    }
                }
            },
            _pushErrorControls: function (errorID) {
                if (!this._errorControlList) {
                    this._errorControlList = new Array();
                }
                var contains = false;
                for (var i in this._errorControlList) {
                    if (this._errorControlList[i] == errorID) {
                        contains = true;
                        break;
                    }
                }
                if (!contains)
                    this._errorControlList.push(errorID);
            },
            _popErrorControls: function (errorID) {
                if (this._errorControlList == null) {
                    return;
                }
                var contains = false;
                for (var i = 0, j = 0; i < this._errorControlList.length; i++) {
                    if (this._errorControlList[i] != errorID) {
                        this._errorControlList[j++] = this._errorControlList[i];
                    }
                    else {
                        contains = true;
                    }
                }
                if (contains) {
                    this._errorControlList.length -= 1;
                }
            },
            _showTooltips: function (e, msg) {
                if (!this._errorPopUp) {
                    this._errorPopUp = document.createElement("div");
                    this._errorPopUp.setAttribute("class", "validatorCalloutTooltip");
                    document.body.appendChild(this._errorPopUp);
                }
                var x = e.offsetLeft;
                var y = e.offsetTop;
                var parentBounds = $common.getBounds(e);
                this._errorPopUp.innerHTML = msg;
                this._errorPopUp.style.zIndex = e.style.zIndex + 1;
                var bounds = new Sys.UI.Bounds(parentBounds.x + parentBounds.width + 5, parentBounds.y, 40, 20);
                $common.setLocation(this._errorPopUp, bounds);
                $common.setVisible(this._errorPopUp, true);

            },
            _hideTootips: function () {
                if (this._errorPopUp) {
                    $common.setVisible(this._errorPopUp, false);
                }
            },
            numericCheck: function (nr) {
                nr = nr.replace(/,/g, ''); //convert to int
                var nArgs = arguments.length;
                var nCount = 0;
                var nPointIndex = -1;
                var nSignIndex = -1;
                for (var i = 0; i < nr.length; i++) {
                    var ch = nr.substr(i, 1);
                    if (ch < "0" || ch > "9") {
                        if (ch == ".") {
                            if (nPointIndex != -1) {
                                alert("数字类型只能有一个小数点");
                                return false;
                            }
                            else
                                nPointIndex = i;
                        }
                        else if (ch == "-" || ch == "+") {
                            if (nSignIndex != -1) {
                                alert("数字类型只能有一个\"" + ch + "\"");
                                return false;
                            }
                            else
                                nSignIndex = i;
                        }
                        else if (ch != ",")	//过滤掉数字
                        {
                            alert("必需输入合法的数字");
                            return false;
                        }
                    }
                }

                if (nPointIndex == -1)
                    nPointIndex = nr.length;

                if (nArgs > 1)	//参数个数大于1
                {
                    var nNumber = nr * 1;
                    var intDigit = arguments[1];
                    var fracDigit;
                    var minValue;
                    var maxvalue;

                    if (nArgs > 2) {
                        fracDigit = arguments[2];
                        if (nArgs > 3) {
                            minValue = arguments[3];
                            if (nArgs > 4)
                                maxValue = arguments[4];
                        }
                    }
                }

                if (typeof (intDigit) != "undefined" && (nr.substring(0, nPointIndex) * 1).toString().length > intDigit) {
                    alert("整数部分的位数不能超过" + intDigit + "位");
                    return false;
                }

                var strFrac = nr.substring(nPointIndex + 1, nr.length);

                if (strFrac.length > 0) {
                    strFrac = "0." + strFrac;
                    if (typeof (fracDigit) != "undefined" && (strFrac * 1).toString().length - 2 > fracDigit) {
                        alert("小数部分的位数不能超过" + fracDigit + "位");
                        return false;
                    }
                }

                if (typeof (minValue) != "undefined" && typeof (maxValue) != "undefined") {
                    if ((nr * 1) < minValue || (nr * 1) > maxValue) {
                        alert("数字必需在" + minValue + "和" + maxValue + "之间");
                        return false;
                    }
                }
                else if (typeof (minValue) != "undefined") {
                    if ((nr * 1) < minValue) {
                        alert("数字必需大于等于" + minValue);
                        return false;
                    }
                }
                else if (typeof (maxValue) != "undefined") {
                    if ((nr * 1) > maxValue) {
                        alert("数字必需小于等于" + maxValue);
                        return false;
                    }
                }
                return true;
            },

            formatData: function (e) {
                var validControl = this.findvalidControl(e.target);
                if (validControl == null) return;
                e.target.value = this.formatNumber(e.target.value, validControl[1].FormatString);
            },

            formatNumber: function (strExp, strFmt) {
                var vResult;
                var objFmt;
                var nI, nJ;
                strExp = strExp.replace(/(,)|(\D)/g, '');
                if (isNaN(strExp))
                    return false;

                vResult = new Number(strExp);
                objFmt = this.paramFmt(strFmt);

                //根据格式串定义，对vResult进行舍入；结果整数部分->strIntPrt，小数部分->strDecPart；
                vResult *= Math.pow(10, objFmt.DecRndCount);
                vResult = Math.round(vResult);
                vResult = vResult.toString();

                var strIntPart, strDecPart;

                with (vResult) {
                    strIntPart = substr(0, length - objFmt.DecRndCount);
                    strDecPart = substr(length - objFmt.DecRndCount, objFmt.DecRndCount);
                    //去除小数部分尾部多余的零；
                    strDecPart = (Math.pow(10, -objFmt.DecRndCount) * strDecPart.valueOf()).toString();
                    strDecPart = strDecPart.substr(2, objFmt.DecRndCount);
                }

                //定长整数部分(前补零)及小数部分(后补零)；
                for (nI = strIntPart.length; nI < objFmt.IntFixLen; nI++)
                    strIntPart = "0" + strIntPart;

                for (nI = strDecPart.length; nI < objFmt.DecFixLen; nI++)
                    strDecPart = strDecPart + "0";

                //整数部分根据格式串就位；
                var strBuf, aBuf;

                strBuf = objFmt.IntPart.replace(/#/g, "0");
                aBuf = strBuf.split("0");
                if (aBuf.length) {
                    strBuf = aBuf[aBuf.length - 1];
                    for (nI = aBuf.length - 2, nJ = strIntPart.length - 1; nI >= 0; nI--, nJ--)
                        strBuf = aBuf[nI] + strIntPart.charAt(nJ) + strBuf;

                    if (nJ >= 0)
                        strBuf = strIntPart.substr(0, nJ + 1) + strBuf;

                    strIntPart = strBuf;
                }

                //小数部分根据格式串就位；
                strBuf = objFmt.DecPart.replace(/#/g, "0");
                aBuf = strBuf.split("0");
                if (aBuf.length) {
                    strBuf = aBuf[0];
                    for (nI = 1, nJ = 0; nI < aBuf.length; nI++, nJ++)
                        strBuf = strBuf + strDecPart.charAt(nJ) + aBuf[nI];

                    if (nJ < strDecPart.length)
                        strBuf = strBuf + strIntPart.substr(nJ);

                    strDecPart = strBuf;
                }

                //处理逗分数值表示法；
                if (strIntPart.search(/,/g) >= 0)
                    strIntPart = this.numCommaSplit(strIntPart);

                //合并整数部分和小数部分，返回；
                if (strDecPart.length > 0)
                    strDecPart = "." + strDecPart;

                return strIntPart + strDecPart;
            },
            paramFmt: function (strFmt) {
                if (strFmt.indexOf(':') >= 0) {
                    strFmt = strFmt.substr(strFmt.indexOf(':') + 1, strFmt.length - strFmt.indexOf(':') - 2);
                }
                var objFmt = new Object();
                var nPointPos;
                var nZeroPos;

                nPointPos = strFmt.search(/\./g);
                if (nPointPos < 0)
                    nPointPos = strFmt.length

                //确定格式串的整数部分、小数部分及舍入位数；
                objFmt.IntPart = strFmt.substr(0, nPointPos);
                objFmt.DecPart = strFmt.substr(nPointPos + 1);
                objFmt.DecRndCount = this.statCharCount(objFmt.DecPart, '0', '#');

                //确定整数部分的最小长度；
                with (objFmt.IntPart) {
                    nZeroPos = search(/0/g);
                    if (nZeroPos < 0)
                        nZeroPos = length;

                    objFmt.IntFixLen = this.statCharCount(substr(nZeroPos), '0', '#');
                }

                //确定小数部分的最小长度；
                with (objFmt.DecPart) {
                    var aMatch = match(/0/g);
                    if (aMatch == null)
                        objFmt.DecFixLen = 0
                    else
                        objFmt.DecFixLen = this.statCharCount(substr(0, aMatch.lastIndex), '0', '#');
                }

                return objFmt;
            },

            //以下为格式化数字程序
            statCharCount: function (str, chr) {
                var aMatch;
                var strPattern = chr;
                var nI;

                for (nI = 2; nI < arguments.length; nI++)
                    strPattern = strPattern.concat("|", arguments[nI]);

                aMatch = str.match(new RegExp(strPattern, "g"));

                if (aMatch == null)
                    return 0;
                else
                    return aMatch.length;
            },

            numCommaSplit: function (str) {
                var nI;
                var strBuf = "";
                var bNegative = false;

                //if negative get rid of "-"
                if (str.substr(0, 1) == "-") {
                    str = str.substr(1);
                    bNegative = true;
                }

                str = this.getRidOfChar(str, ',');

                for (nI = str.length - 3; nI > 0; nI -= 3)
                    strBuf = "," + str.substr(nI, 3) + strBuf;

                strBuf = str.substr(0, 3 + nI) + strBuf;

                //if Negative add "-"
                if (bNegative)
                    strBuf = "-" + strBuf;

                return strBuf;
            },

            getRidOfChar: function (str, chr) {
                var aBuf;
                var strBuf = "";
                var nI;

                aBuf = str.split(",");

                if (aBuf != null) {
                    for (nI = 0; nI < aBuf.length; nI++)
                        strBuf = strBuf + aBuf[nI];
                    return strBuf;
                }
                else
                    return "";
            },
            get_validButtons: function () {

                if (this._validButtons)
                    return this._validButtons;
            },
            set_validButtons: function (value) {
                this._validButtons = value;
            },
            get_IsControlsValueChanged: function () {

                if (this._IsControlsValueChanged)
                    return this._IsControlsValueChanged;
            },
            set_IsControlsValueChanged: function (value) {
                this._IsControlsValueChanged = value;
            },
            get_clientDataBind: function () {

                if (this._clientDataBind)
                    return this._clientDataBind;
            },
            set_clientDataBind: function (value) {
                this._clientDataBind = value;
            }, //客户端绑定时的webservice路径
            get_servicePath: function () {

                if (this._servicePath)
                    return this._servicePath;
            },
            set_servicePath: function (value) {
                this._servicePath = value;
            }, //service Method
            ////客户端绑定时的webservice方法
            get_serviceMethod: function () {

                if (this._serviceMethod)
                    return this._serviceMethod;
            },
            set_serviceMethod: function (value) {
                this._serviceMethod = value;
            },
            //操作模式
            get_operationMode: function () {

                if (this._operationMode)
                    return this._operationMode;
            },
            set_operationMode: function (value) {
                this._operationMode = value;
            },
            //新增按钮ID
            get_addOperationControlID: function () {

                if (this._addOperationControlID)
                    return this._addOperationControlID;
            },
            set_addOperationControlID: function (value) {
                this._addOperationControlID = value;
            },
            //编辑按钮ID
            get_editOperationControlID: function () {

                if (this._editOperationControlID)
                    return this._editOperationControlID;
            },
            set_editOperationControlID: function (value) {
                this._editOperationControlID = value;
            },
            //删除按钮ID
            get_delOperationControlID: function () {

                if (this._delOperationControlID)
                    return this._delOperationControlID;
            },
            set_delOperationControlID: function (value) {
                this._delOperationControlID = value;
            },
            //清空数据按钮ID
            get_clearOperationControlID: function () {

                if (this._clearOperationControlID)
                    return this._clearOperationControlID;
            },
            set_clearOperationControlID: function (value) {
                this._clearOperationControlID = value;
            },
            //清空数据按钮ID
            get_applyOperationControlID: function () {

                if (this._applyOperationControlID)
                    return this._applyOperationControlID;
            },
            set_applyOperationControlID: function (value) {
                this._applyOperationControlID = value;
            }

        }
        // Register the class as a type that inherits from Sys.UI.Control.
        $DataBind.registerClass('Kevin.Controls.DataBind', Sys.UI.Control);
        //Sys.registerComponent(Kevin.Controls.DataBind, { name: "DataBind", parameters: { name: "validatorAttributes", type: "string"} });
        //if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
        Kevin.Controls.OperationMode = function () {
            throw Error.invalidOperation();
        }
        Kevin.Controls.OperationMode.prototype = {
            Add: 0,
            Edit: 1,
            View: 2,
            Del: 3,
            Apply: 4,
            Check: 5,
            Pass: 6
        }
        Kevin.Controls.OperationMode.registerEnum("Kevin.Controls.OperationMode", false)

    } // execute

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript(scriptName, ["DataBind"], execute);
    }
    else {
        execute();
    }

})();